package com.saturn.auth;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONObject;

import com.saturn.app.db.DymaticCondition;
import com.saturn.app.db.ListData;
import com.saturn.app.db.ORMapping;
import com.saturn.app.db.ResultORMapping;
import com.saturn.app.db.SimpleDaoTemplate;
import com.saturn.app.exception.BSException;

public class Resource {

	private String id;
	private String name;
	private String path;
	private String parentId;
	private String checked;
	
	private List<Resource> child;

	private static ORMapping<Resource> mapping = new ResultORMapping<Resource>();

	public static int add(Resource role) {
		if (get(role.getId()) != null) {
			throw new BSException("资源ID重复,id=" + role.getId());
		}

		return SimpleDaoTemplate.update(
				"INSERT INTO app_resources VALUES(?, ?, ?, ?)", role.getId(),
				role.getName(), role.getPath(), role.getParentId());
	}

	public static int edit(Resource role) {
		return SimpleDaoTemplate
				.update(
						"UPDATE app_resources SET name = ?, path = ?, parentId = ? WHERE id = ?",
						role.getName(), role.getPath(), role.getParentId(),
						role.getId());
	}

	public static Resource get(String id) {
		return SimpleDaoTemplate.queryOne(
				"SELECT * FROM app_resources WHERE 1 = 1",
				new DymaticCondition().addCondition("and id = '?'", id),
				mapping, Resource.class);
	}

	public static ListData<Resource> getResources(Resource resource,
			String start, String offset, String orderBy, String order) {
		DymaticCondition addCondition = new DymaticCondition()
				.addSimpleCondition(resource, "id", "name", "path", "parentId");

		int total = SimpleDaoTemplate.queryCount(
				"SELECT count(*) FROM app_resources WHERE 1 = 1", addCondition);

		List<Resource> list = SimpleDaoTemplate.query(
				"SELECT * FROM app_resources WHERE 1 = 1", addCondition
						.addCondition("ORDER BY {0} {1}", orderBy, order)
						.addCondition("LIMIT {0}, {1}", start, offset),
				mapping, Resource.class);

		return new ListData<Resource>(total, list);
	}

	public static List<Resource> getResourcesByRoleId(String roleId) {

		return SimpleDaoTemplate
				.query(
						"SELECT id,NAME,path,parentId,CASE WHEN (id  IN (SELECT auth_re_role_resource.resourceId FROM auth_re_role_resource WHERE auth_re_role_resource.roleId='"
								+ roleId
								+ "')) THEN 'true' ELSE null END AS checked FROM app_resources",
						null, new ORMapping<Resource>() {

							@Override
							public void mappingResult(ResultSet rs, Resource t)
									throws SQLException {
								t.setId(rs.getString("id"));
								t.setName(rs.getString("name"));
								t.setPath(rs.getString("path"));
								t.setParentId(rs.getString("parentId"));
								t.setChecked(rs.getString("checked"));
							}
						}, Resource.class);
	}

	public static List<Resource> getResourcesByOrganizationId(
			String organizationId) {

		return SimpleDaoTemplate
				.query(
						"SELECT id,NAME,path,parentId,CASE WHEN (id  IN (SELECT auth_re_organization_resource.resourceId FROM auth_re_organization_resource WHERE auth_re_organization_resource.organizationId='"
								+ organizationId
								+ "')) THEN 'true 'ELSE null END AS checked FROM app_resources",
						null, new ORMapping<Resource>() {

							@Override
							public void mappingResult(ResultSet rs, Resource t)
									throws SQLException {
								t.setId(rs.getString("id"));
								t.setName(rs.getString("name"));
								t.setPath(rs.getString("path"));
								t.setParentId(rs.getString("parentId"));
								t.setChecked(rs.getString("checked"));
							}
						}, Resource.class);

	}

	public static List<Resource> getResourcesByUserId(String userId) {

		return SimpleDaoTemplate
				.query(
						"SELECT id,NAME,path,parentId,CASE WHEN (id  IN (SELECT auth_re_user_resource.resourceId FROM auth_re_user_resource WHERE auth_re_user_resource.userId='"
								+ userId
								+ "')) THEN 'true 'ELSE null END AS checked FROM app_resources",
						null, new ORMapping<Resource>() {

							@Override
							public void mappingResult(ResultSet rs, Resource t)
									throws SQLException {
								t.setId(rs.getString("id"));
								t.setName(rs.getString("name"));
								t.setPath(rs.getString("path"));
								t.setParentId(rs.getString("parentId"));
								t.setChecked(rs.getString("checked"));
							}
						}, Resource.class);

	}

	/**
	 * 获得用户登录菜单资源
	 * 
	 * @param userId
	 */
	public static List<Resource> getAllResouceByUserId(String userId,
			String parentId) {

		String sql = "SELECT * FROM app_resources WHERE id IN("
				+ "SELECT oRe.resourceId FROM auth_re_organization_resource AS oRe, auth_re_organization_user AS oUS WHERE "
				+ "oRe.organizationId = oUS.organizationId AND oUs.userId ='"
				+ userId
				+ "' UNION SELECT rRe.resourceId FROM auth_re_role_resource AS rRe, auth_re_user_role AS URo WHERE rRe.roleId = "
				+ "URo.roleId AND URo.userId ='"
				+ userId
				+ "' UNION SELECT resourceId FROM auth_re_user_resource WHERE userId='"
				+ userId + "')";
		if (parentId == null) {
			sql += "and parentId is null";
		} else {
			sql += "and parentId ='" + parentId + "'";
		}

		return SimpleDaoTemplate.query(sql, null, mapping, Resource.class);
	}
	
	public static List<Resource> getAllResouceByUserId(String userId) {
		List<Resource> roots = Resource.getAllResouceByUserId(userId, null);
		LinkedList<Resource> queue = new LinkedList<Resource>(roots);
		
		while (!queue.isEmpty()) {
			Resource resource = queue.removeFirst();
			
			List<Resource> children = Resource.getAllResouceByUserId(userId, resource.getId());
			resource.setChild(children);
			queue.addAll(children);
		}
		
		return roots;
	}
	
	public static int remove(String id) {
		return SimpleDaoTemplate.update(
				"DELETE FROM app_resources WHERE id = ?", id);
	}

	public static void removes(String[] ids) {
		if (ids != null) {
			for (String id : ids) {
				remove(id);
			}
		}
	}

	public Resource() {
	}

	public Resource(String id, String name, String path, String parentId,
			String checked) {
		super();
		this.id = id;
		this.name = name;
		this.path = path;
		this.parentId = parentId;
		this.checked = checked;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	@Override
	public String toString() {
		return new JSONObject(this).toString().replace("parentId", "_parentId");
	}

	public String getChecked() {
		return checked;
	}

	public void setChecked(String checked) {
		this.checked = checked;
	}

	public List<Resource> getChild() {
		return child;
	}

	public void setChild(List<Resource> child) {
		this.child = child;
	}

	public static void main(String[] args) {
		System.out.println(new Resource());
	}
}
